layui.use(['layer','form','table','element','layedit','upload','laydate'],function () {
    var layer = layui.layer
        ,form = layui.form
        ,table =layui.table
        ,layedit = layui.layedit
        ,laydate = layui.laydate
        ,upload = layui.upload;

    //日期时间选择器
    laydate.render({
        elem: '#byDate'
        ,type: 'datetime'
    });

    //动态加载type和label
    $.ajax({
        type:"GET",
        url:"/admin/project/getLabelAndType",
        success:function (result) {
            var typeList = result.data.labelTypeList.typeList;

            $.each(typeList,function (i,type) {
                var typeName = type.typeName;
                var id = type.id;
                if(typeName == "薅羊毛"){
                    $("#types").append("<input type='radio' checked  name='type' title='"+typeName+"' value='"+id+"'></input>");
                }else {
                    $("#types").append("<input type='radio'  name='type' title='"+typeName+"' value='"+id+"'></input>");
                }

             });

            form.render();
        },
        error:function () {
            layer.msg("系统错误！");
        }
    });

    // var index = layedit.build('addEdit', {
    //     tool: [
    //          'strong', 'italic', 'underline', 'del',
    //         ,'addhr' //添加水平线
    //         ,'|', 'fontFomatt','fontfamily','fontSize', //段落格式，字体样式，字体颜色
    //         , 'colorpicker', 'fontBackColor'//字体颜色，字体背景色
    //                 , 'face', '|', 'left', 'center', 'right', '|', 'link', 'unlink'
    //                 ,'image'//原版上传图片
    //                 ,'images'//多图上传
    //                 , 'image_alt'//上传图片拓展
    //                 ,'anchors' //锚点
    //                 , '|', 'table'//插入表格
    //                 ,'customlink'//插入自定义链接
    //                 ,'fullScreen'//全屏
    //         ]
    //     , height: 600
    //     ,   uploadImage: {
    //         url: '/admin/project/uploadProjectImg'
    //         ,type: 'post' //默认post
    //     }
    // });

    var E = window.wangEditor
    var editor = new E('#addEdit')
    // 或者 var editor = new E( document.getElementById('editor') )
    editor.customConfig.uploadImgServer = '/admin/project/uploadProjectImg2'
    editor.customConfig.uploadFileName = 'file'
    // 自定义菜单配置
    editor.customConfig.menus = [
        'head',  // 标题
        'fontSize',  // 字号
        'foreColor',  // 文字颜色
        'backColor',  // 背景颜色
        'link',  // 插入链接
        'justify',  // 对齐方式
        'quote',  // 引用
        'image',  // 插入图片
        'undo',  // 撤销
        'redo',  // 重复，
        'qsy'  // 去水印
    ]
    editor.create();


    //普通图片上传
    var uploadInst = upload.render({
        elem: '#update_cover_btn'
        ,url: '/admin/project/uploadImg?type=appCover'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#demo1').attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //如果上传失败
            console.log(res);
            var flag = res.flag;
            var message = res.message;
            if(!flag){
                layer.msg(message);
            }else{
                //上传成功,则返回url
                layer.msg("封面上传成功!");
                $("#cover_img").attr("value",res.data.url);
            }
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });

    //普通图片上传
    var uploadInst2 = upload.render({
        elem: '#update_cover_btn2'
        ,url: '/admin/project/uploadImg?type=appInvateImg'
        ,auto:false
        ,bindAction: '#btnUpload'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#demo2').attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //如果上传失败
            console.log(res);
            var flag = res.flag;
            var message = res.message;
            if(!flag){
                layer.msg(message);
            }else{
                //上传成功,则返回url
                layer.msg("封面上传成功!");
                $("#cover_img2").attr("value",res.data.url);
            }
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText2');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst2.upload();
            });
        }
    });

    //普通图片上传
    var uploadInst3 = upload.render({
        elem: '#update_cover_btn3'
        ,url: '/admin/project/uploadImg?type=appCover'
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#demo3').attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //如果上传失败
            console.log(res);
            var flag = res.flag;
            var message = res.message;
            if(!flag){
                layer.msg(message);
            }else{
                //上传成功,则返回url
                layer.msg("封面上传成功!");
                $("#cover_img3").attr("value",res.data.url);
            }
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText3');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst3.upload();
            });
        }
    });

    //表单验证
    form.verify({
        id:function (value) {
            if(value == ""){
                return "id不能为空";
            }
        },
        cover:function (value) {
        },
        content:function () {
            var content = editor.txt.text();
            if(content == "" || content.length==0){
                return "内容不能为空";
            }
        }
    });


    //提交表单
    form.on('submit(form)',function (data) {

        //校验类型和标签是否选择
        layer.msg('保存中...', { icon: 16, shade: [0.5, '#f5f5f5'], scrollbar: false, offset: '50%', time: 300000 });

        var keyword = $("#keyword").val();
        if(keyword != null && keyword != '') {
            keyword = keyword.replaceAll("，",",");
            keyword = keyword.replaceAll("、",",");
        }

        var paramData = {
            "title":$("#title").val(),
            "cover":$("#cover_img").val(),
            "mark":$("#mark").val(),
            "inviteImg":$("#cover_img2").val(),
            "inviteUrl":$("#invite_url").val(),
            "withdraw":$("#cover_img3").val(),
            "downCount":$("#down_count").val(),
            "falseDownCount":$("#false_down_count").val(),
            "content":editor.txt.html(),
            "device":$('input[name="device"]:checked ').val(),
            "keyword":keyword,
            "companyName":$("#companyName").val(),
            "type":$("#type").val()
        };

        var data2 = JSON.stringify(paramData);

        //保存项目
        $.ajax({
            url:"/admin/app/save",
            type:"POST",
            data:data2,
            // dataType:"json",
            contentType:"application/json;charset=utf-8",
            success:function (result) {
                // console.log("data=="+form_data)
                if(result.flag){
                    layer.msg(result.message);
                    //清空内容
                    // $("#form").reset();
                    document.getElementById("form").reset();
                    layui.form.render();
                }else{
                    layer.msg(result.message);
                }
            },
            error:function () {
                layer.msg("系统错误！");
            }
        });

    });

    $("#createInviteImgBtn").bind("click",function () {
        var url = $("#invite_url").val();
        var xhr = new XMLHttpRequest()
        xhr.open('GET', "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data="+url, true);
        xhr.responseType = 'blob';
        xhr.onload = function(res){
            var data = new FormData();
            data.append("file",res.target.response);
            $.ajax({
                url:"/admin/project/uploadImg?type=appInvateImg",
                type:"POST",
                data:data,
                dataType: 'json', //以jsonp类型返回
                async: false,//同步上传
                cache: false,//上传文件无需缓存
                processData: false,  // 不处理数据
                contentType: false, // 不设置内容类型
                success:function (result) {
                    $('#demo2').attr('src', "https://daydayzhuan.oss-cn-shenzhen.aliyuncs.com/"+result.data.url); //图片链接（base64）
                    $("#cover_img2").val(result.data.url);
                },
                error:function () {
                    layer.msg("系统错误！");
                }
            });
        };
        xhr.send();
    })

});

